/*

     PlAr is Platform Arena: a 2D multiplayer shooting game
     Copyright (C) 2009 Ragagnin Antonio <spocchio@gmail.com>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package plar.demo;

import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.GraphicsDevice;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.*;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OptionalDataException;
import java.util.ArrayList;
import java.util.HashMap;

import javax.imageio.ImageIO;
import javax.imageio.stream.FileImageInputStream;
import javax.swing.JOptionPane;

import plar.ClientServer.Client;
import plar.ClientServer.ShownElement;
import plar.core.Common;
import plar.core.Sprite;

/**
 * 
 * @author spok
 */
public class GamePanel extends javax.swing.JPanel  {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	HashMap<String, BufferedImage> bufferedImages;
	ArrayList<ShownElement> elementi;
	public boolean catchinput = true;
	public int index = 0;
	Rectangle speedpos;
	String chat;
	public int delay;
	BufferedImage bufferedImage; 
    Graphics2D g2;
    Point resolution;

	public GamePanel(Point p) {
	super();
    elementi = new ArrayList<ShownElement>();
	bufferedImages = new HashMap<String, BufferedImage>();
	chat =  new String();
	resolution = new Point (p);
	}

	private void initComponents() {
	
	}
long lastRefresh = 0;
	public void paintComponent(Graphics g) {

		long thistime  = java.util.Calendar.getInstance().getTimeInMillis();
		long delta = thistime - lastRefresh;
		lastRefresh = thistime;
		
		Graphics2D g3 = (Graphics2D) g;
		GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();				
		GraphicsConfiguration gc = gd.getDefaultConfiguration();
		
		if(bufferedImage == null)
		bufferedImage = gc.createCompatibleImage(resolution.x,resolution.y, Transparency.OPAQUE);

		
		Graphics2D g2 = bufferedImage.createGraphics();
		g2.clearRect(0,0,resolution.x,resolution.y);
		
		
		g2.setBackground(new Color(25,25,112));
		g2.setColor(new Color(15,15,20));  
		 g2.fill(new Rectangle(0,0,resolution.x,resolution.y));
		//g2=g3;
	      
	    g2.setColor(Color.cyan);  
		
		if (elementi == null || elementi.size() == 0)
			return;

		for (ShownElement se : elementi) {
			if(!(se.rectangle.x==0 && se.rectangle.y==0 && se.rectangle.width==0  && se.rectangle.height==0))
			{
			Rectangle2D r = new Rectangle2D.Double((double) se.rectangle.x,
					(double) se.rectangle.y, (double) se.rectangle.width,
					(double) se.rectangle.height);
			Sprite currentSprite = se.spriteSet
					.get(index % se.spriteSet.size());

			BufferedImage fungoImg;
			if (bufferedImages.containsKey(currentSprite.getFileName()))
				fungoImg = bufferedImages.get(currentSprite.getFileName());
			else {
			boolean error=false;
				try {

					File file1 = new File(currentSprite.getFileName());
					FileImageInputStream fImg = new FileImageInputStream(file1);
					fungoImg = ImageIO.read(fImg);
				} catch (FileNotFoundException e) {
					Common.info(5,currentSprite.getFileName());
					
				JOptionPane.showMessageDialog(null,
				"Failed loading: "+currentSprite.getFileName()+"\r\nmake sure you have the resources folder here.","Plar",
				JOptionPane.WARNING_MESSAGE);
				throw new RuntimeException("IO Error");
				
				} catch (IOException e) {
				JOptionPane.showMessageDialog(null,
				"Failed loading: "+currentSprite.getFileName()+"\r\nmake sure you have the resources folder here.","Plar",
				JOptionPane.WARNING_MESSAGE);
				throw new RuntimeException("IO Error");
					
				
				}
				
				bufferedImages.put(currentSprite.getFileName(), fungoImg);
				Common.info(7,"loaded: " + currentSprite.getFileName());
			}

			Rectangle position = new Rectangle(se.rectangle);
			if (currentSprite.sizex != 0 )
				position.width = (int)currentSprite.sizex;
			if (currentSprite.sizey != 0)
				position.height =(int) currentSprite.sizey;
			if (currentSprite.offsetx != 0)
				position.x += currentSprite.offsetx;
			if (currentSprite.offsety != 0)
				position.y += currentSprite.offsety;
		
			g2.drawImage(fungoImg, position.x, position.y, position.width+1,
					position.height+1, this);
			// }
			// g2.draw(r);
		}
	}
		g2.drawString(Common.product+" ver:"+Common.version, 10, 20);
		g2.drawString("       to RUN use ARROWS or A,D keys", 10, 40);
		g2.drawString("       to JUMP use UP key or SPACE or W", 10, 52);
		g2.drawString("       to BEND use DOWN or S key", 10, 64);
		g2.drawString("       to AIM'n'FIRE use MOUSE", 10, 78);
	 	g2.drawString("       to change GUN use NUMBERS", 10, 90);
	    g2.drawString("       to CHAT use C key", 10, 102);
		g2.drawString("Framerate: "+(delta)+"ms, delay: "+delay,10,124);
		g2.drawString("Site: http://plar.googlecode.com/",10,150);
		//g2.drawString("Created by "+Common.author+" "+Common.copyright, 10, 170);				
		g2.drawString("Chat:", 10, 200);				
		
		String [] chats = chat.split("\\n");
		int j=0;
		for(int i = 0;i<chats.length;i++)
		{
			g2.drawString(chats[i], 10, 200+j*10);
			//if(chats[i].length()>1)
			j++;
		}
		
		//super.paintComponent(g);	
		//g3.drawImage(bufferedImage, 0, 0, null);
		g3.drawImage(bufferedImage, null,0,0);
		//Common.info("g2.drawString(Framerate: "+(delta)+"ms, delay: "+delay);
	}

	
	public void repaint() {
		super.repaint();
	}

	public void viewOutput(Client c) {

//Common.info("view output?");
		if(c.getClient())
		{
			
			ArrayList<ShownElement> elems;
			try {
				elems = c.getScreen();
				if(elems!=null)		elementi = elems;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
				c.dropClient();
		}
		
		if(Math.random()>0.09)
		{
			if(c.getClient())
			{	
				chat = c.getChat();
			c.dropClient();
			}
		}
		index++;
		repaint();
	}


}
